{% extends 'template/jhTemplateV4.html'%}

{% block vueTemplate %}

<script type="text/html" id="app-template">
<div>
  <v-app mobile-breakpoint="sm">
    <jh-menu />
    <v-main class="mt-15">
      <!-- 头部内容 >>>>>>>>>>>>> -->
      <div class="jh-page-second-bar px-8">
        <v-row class="flex justify-space-between">
          <v-col cols="12" xs="12" sm="12" md="4" xl="3">
            <div class="pt-3 text-h7 font-weight-bold">财务付/收款申请单
              <!-- 帮助页按钮 -->
              <v-icon @click="isHelpPageDrawerShown = true" color="success" small>mdi-help-circle-outline
              </v-icon>
            </div>
            <v-breadcrumbs class="pb-3 pt-0 pl-0" :items="breadcrumbs" divider="-"></v-breadcrumbs>
          </v-col>
          <!-- 搜索条件表单 >>>>>>>> -->
          <v-col cols="12" md="6">
            <v-row class="jh-backend-form-container  justify-end ma-0 py-1 pb-xs-2">
              <v-col cols="12" md="4" class="pa-xs-0 pb-2 pl-1 pl-xs-1">
                <v-select v-model="ticketStatus" color="success" prefix="状态：" class="jh-v-input bg-white" :items="constantObj.ticketStatus" dense filled single-line></v-select>
              </v-col>
              <!-- 申请时间 -->
              <v-col cols="12" md="4" class="pa-xs-0 pb-2 pl-1 pl-xs-1">
                <v-select
                  v-model="serverSearchInput.ticketRequestAt"
                  :close-on-content-click="false" :nudge-right="40" transition="scale-transition" offset-y min-width="290px"
                  class="jh-v-input bg-white"
                  :items="items"
                  prefix="申请时间："
                  dense filled single-line
                  clearable
                  :menu-props="{ button: true, offsetY: true }"
                  multiple
                  :loading="isPeridListLoading">
                </v-select>            
              </v-col>
              <v-btn class="jh-backend-search-btn elevation-0 ml-0 mt-3" color="success" small @click="doUiAction('getTableData')">
                查询
              </v-btn>
            </v-row>
          </v-col>
          <!-- <<<<<<<< 搜索条件表单 -->
        </v-row>
      </div>
      <!-- <<<<<<<<<<<<< 头部内容 -->

      <div class="jh-page-body-container px-8">
        <!-- 页面内容 >>>>>>>>>>>>> -->
        <v-card class="rounded-lg">
          <v-row class="ma-0 pa-4">
            <!-- 按钮 -->
            <div>
              <v-btn color="success" class="elevation-0 mr-2" @click="doUiAction('handleItem', { actionType: '处理'})" :disabled="isTableLoading" small>批量处理</v-btn>
            </div>
            <v-spacer></v-spacer>
            <!-- 搜索过滤 -->
            <v-col cols="12" xs="8" sm="6" md="6" xl="4" class="pa-0 d-flex">
              <v-btn-toggle v-model="searchTicketTypeSwitch" mandatory dense class="mr-2" color="success"> 
                <v-btn small> 所有的 </v-btn> 
                <v-btn small v-for="item, index in constantObj.ticketType" :key="index"> {{item}} </v-btn> 
              </v-btn-toggle>
              <v-text-field color="success" v-model="searchInput" prefix="搜索：" class="jh-v-input" dense filled single-line></v-text-field>
            </v-col>
          </v-row>
          <!-- 表格 -->
          <v-data-table
            :headers="headers"
            :items="tableDataFilter"
            :search="searchInput"
            :footer-props="{ itemsPerPageOptions: [20, 50, -1], itemsPerPageText: '每页', itemsPerPageAllText: '所有'}"
            :items-per-page="-1"
            mobile-breakpoint="0"
            :loading="isTableLoading"
            checkbox-color="success"
            :class="{'zebraLine': isTableZebraLineShown }"
            fixed-header
            class="jh-fixed-table-height elevation-0 mt-0 mb-xs-4"
            show-select item-key="ticketId" @item-selected="tableItemSelected" v-model="tableSelected" @toggle-select-all="tableToggleSelectAll">
            <!-- 表格操作按钮 -->
            <template v-slot:item.action="{ item }">
              <span v-if="_.includes(['完成', '拒绝'], item.ticketStatus)" role="button" class="success--text font-weight-medium font-size-2 mr-2" @click="doUiAction('handleItem', { item, actionType: '查看'})">
                <v-icon size="16" class="success--text">mdi-eye-outline</v-icon>查看
              </span>
              <span v-else role="button" class="success--text font-weight-medium font-size-2 mr-2" @click="doUiAction('handleItem', { item, actionType: '处理'})">
                <v-icon size="16" class="success--text">mdi-note-edit-outline</v-icon>处理
              </span>
            </template>
            <template v-slot:item.ticketStatus="{ item }">
              <v-chip dark x-small :color="constantObj.ticketStatusColor[item.ticketStatus]">
                {{item.ticketStatus}}
              </v-chip>
            </template>
            <template v-slot:item.ticket-request-at="{ item }">
              {{item.ticketRequestAt | dateFormat}}
            </template>
            <template v-slot:item.ticket-status-at="{ item }">
              {{item.ticketStatusAt | dateFormat}}
            </template>
            <template v-slot:item.operation-at="{ item }">
              {{item.operationAt | dateFormat}}
            </template>
            <template v-slot:item.remindDaysText="{ item }">
              <span :class="{'red--text': item.remindDays !== null && item.remindDays <= 3}">{{_.includes(['完成', '拒绝'], item.ticketStatus) ? '-' : item.remindDaysText}}</span>
            </template>
            <!-- 没有数据 -->
            <template v-slot:loading>
              <div class="jh-no-data">数据加载中</div>
            </template>
            <template v-slot:no-data>
              <div class="jh-no-data">暂无数据</div>
            </template>
            <template v-slot:no-results>
              <div class="jh-no-data">暂无数据</div>
            </template>
            <!-- 表格分页 -->
            <template v-slot:footer.page-text="pagination">
              <span>{{pagination.pageStart}}-{{pagination.pageStop}}</span>
              <span class="ml-1">共{{pagination.itemsLength}}条</span>
            </template>
          </v-data-table>
        </v-card>

        <paymentRequest-handle ref="handlePaymentRequest" @success="doUiAction('getTableData')" />
      </div>

      <!-- 帮助页抽屉 >>>>>>>>>>>>> -->
      <v-navigation-drawer v-model="isHelpPageDrawerShown" :permanent="isHelpPageDrawerShown" fixed temporary right width="80%" class="elevation-24">
        <iframe style="border: 0" :src="`/${appInfo.appId}/pageDoc#404.md`" width="100%" height="100%"></iframe>
        <v-btn elevation="0" color="success" fab absolute top left small tile class="drawer-close-float-btn" @click="isHelpPageDrawerShown = false">
          <v-icon>mdi-close</v-icon>
        </v-btn>
      </v-navigation-drawer>
      <!-- <<<<<<<<<<<<< 帮助页抽屉 -->

    </v-main>
  </v-app>

  <jh-toast />
  <jh-mask />
  <jh-confirm-dialog />
</div>
</script>

<div id="app">
</div>

{% endblock %}

{% block vueScript %}

{% include 'common/jianghuJs/fixedTableHeightV4.html' %}
{% include 'common/constantUtil.html' %}

{% include 'component/voucher/vueFilters.html' %}

{% include 'component/ticket/paymentRequest-handle.html' %}


<script type="module">
  new Vue({
    el: '#app',
    template: '#app-template',
    vuetify: new Vuetify(),
    filters: {

    },
    data: () => ({
      // 面包屑
      breadcrumbs: [
        {
          text: '首页',
          disabled: true,
        },
        {
          text: '财务付/收款申请单',
          disabled: true,
        }
      ],
      isHelpPageDrawerShown: false,
      isHelpPageDrawerLoaded: false,

      // 表格相关数据
      isTableZebraLineShown: true,
      validationRules: {
        requireRules: [
          v => !!v || '必填',
        ],
      },
      // 下拉选项
      constantObj: {
        ticketStatus: [
          {text: '全部', 'value': null},
          {text: '申请付/收款', 'value': ['申请','处理中']},
          {text: '完成', 'value': ['完成','拒绝']},
        ],
        ticketStatusColor: { '申请': 'warning', '处理中': 'blue', '拒绝': 'error', '完成': 'success', },
        ticketType: ['保养付款', '保险付款', '发车收款', '退车付款'],
        customer: [],
        supplier: [],
      },
      ticketStatus: ['申请','处理中'],
      serverSearchInput: {
        ticketRequestAt: []
      },
      isServerSearchDateMenuShown: false,
      searchTicketTypeSwitch: 0,
      searchInput: null,
      isTableLoading: true,
      tableData: [],
      tableDataFilter: [],
      headers: [
        { text: '操作', value: 'action', align: 'center', sortable: false, width: 120, class: 'fixed', cellClass: 'fixed' },
        { text: "剩余账期", value: "remindDaysText", width: 80 },
        { text: "收付款人/供货商", value: "payee", width: 80 },
        { text: "申请单ID", value: "ticketId", width: 120 },
        { text: "状态", value: "ticketStatus", width: 120 },
        { text: "业务Id", value: "ticketBizId", width: 120 },
        { text: "类型", value: "ticketType", width: 120 },
        { text: "申请金额", value: "ticketRequestAmount", width: 120 },
        { text: "申请描述", value: "ticketDesc", width: 120 },
        { text: "申请时间", value: "ticket-request-at", width: 120 },
        { text: "处理时间", value: "ticket-status-at", width: 120 },
        { text: "状态描述", value: "ticketStatusDesc", width: 120 },
        { text: "操作者", value: "operationByUser", width: 120 },
        { text: "操作时间", value: "operation-at", width: 250 },
      ],
      tableSelected: [],

      handleActionType: '',
      handleTicketIds: [],
      handleTicketList: [],
      items: [],
      isPeridListLoading: true,
    }),
    computed: { },
    watch: {
      searchTicketTypeSwitch(){
        this.tableSelected = [];
        this.ticketTypeSwitch();
      }
    },
    async created() {
     },
    async mounted() {
      await this.doUiAction('preparePageBaseData')
      await this.doUiAction('getTableData');
    },
    methods: {
      async doUiAction(uiActionId, uiActionData) {
        try {
          switch (uiActionId) {
            case 'preparePageBaseData':
              await this.getCustomerData();
              break;
            case 'getTableData':
              await this.getTableData();
              await this.ticketTypeSwitch();
              break;
            case 'handleItem':
              await this.prepareDoHandleItem(uiActionData);
              await this.prepareHandleValidate();
              await this.doHandleItem();
              break;
            default:
              console.error("[doUiAction] uiActionId not find", { uiActionId });
              break;
          }
        } catch (error) {
          await window.jhMask.hide();
          throw error;
        }
      },

      // ---------- 预备数据 uiAction >>>>>>>>>>>> --------
      async getCustomerData() {
        const rows = (await window.jianghuAxios({
          data: {
            appData: {
              pageId: 'paymentTicketRequest',
              actionId: 'selectCustomerList',
              actionData: {},
              where: {},
              orderBy: [{ column: 'idSequence', order: 'desc' }]
            }
          }
        })).data.appData.resultData.rows;
        this.constantObj.customer = rows;
      },
      // ---------- <<<<<<<<<<< 预备数据 uiAction ---------
     
      // ---------- 获取数据 uiAction >>>>>>>>>>>> --------
       async getTableData() {
                
        const filterServerSearchInput = this.serverSearchInput.ticketRequestAt.map(item => ['["ticketRequestAt", "like", "' +item+'%"]']);
        const filterTicketRequestAt  = '[' + filterServerSearchInput + ']'
        const filterRecord = JSON.parse(filterTicketRequestAt)

        this.isTableLoading = true;

        const serverSearchInput = _.cloneDeep(this.serverSearchInput);
        const whereIn = _.pickBy({
          ticketType: this.constantObj.ticketType,
          ticketStatus: this.ticketStatus
        }, _.identity);
        delete serverSearchInput.ticketStatus;
        const backendSearchData = _.pickBy(serverSearchInput, _.identity);
        
        const rows = (await window.jianghuAxios({
          data: {
            appData: {
              pageId: 'paymentTicketRequest',
              actionId: 'selectTicketList',
              actionData: {},
              whereOrOptions: filterRecord,
              whereIn,
              orderBy: [{ column: 'operationAt', order: 'desc' }]
            }
          }
        })).data.appData.resultData.rows;

        this.tableData = rows.map(row => {
          row.ticketContentRequest = JSON.parse(row.ticketContentRequest);
          row.payee = row.ticketContentRequest?.supplierInfo?.supplierName || row.ticketContentRequest?.customerInfo?.customerName;
          row.remindDays = this.computedDays(row);
          row.remindDaysText = row.remindDays === null ? '' : `${row.remindDays}天`;
          return row;
        });
        this.tableSelected = [];
        this.isTableLoading = false;
        this.isPeridListLoading = false;
        rows.forEach(item => {
          const period = item.ticketRequestAt.slice(0, 7);
          const {ticketRequestAt} = item
          this.items.push(period)
          });

      },
      computedDays(item) {
        const { ticketStatus, ticketContentRequest: { paymentRequiredAt, supplierInfo, customerInfo } } = item;

        if(_.includes(['完成', '拒绝'], ticketStatus) || !paymentRequiredAt) {
          return null;
        }

        const paymentCycleInfo = supplierInfo || customerInfo;
        if(paymentCycleInfo && !isNaN(paymentCycleInfo.supplierPaymentCycle || paymentCycleInfo.customerCollectionCycle)) {
          const remindMillseconds = dayjs(paymentRequiredAt) - dayjs();
          const remindDays = Math.ceil(remindMillseconds / (24 * 3600 * 1000));
          return isNaN(remindDays) ? 0 : remindDays;
        }

        return null;
      },
      ticketTypeSwitch(){
        this.tableDataFilter = this.searchTicketTypeSwitch === 0 ? this.tableData : _.filter(this.tableData, {ticketType: this.constantObj.ticketType[this.searchTicketTypeSwitch - 1]});
      },
      // ---------- <<<<<<<<<<< 获取数据 uiAction ---------
     
      // ---------- 处理工单 uiAction >>>>>>>>>>>> --------
      async prepareDoHandleItem(funData) {
        const { item, actionType } = funData;
        const ticketList = item ? [item] : this.tableSelected;
        this.handleTicketList = ticketList;
        this.handleActionType = actionType;
        this.handleTicketIds = _.map(ticketList, 'ticketId');
      },
      async prepareHandleValidate() {
        const { handleTicketList } = this;
        if(handleTicketList.length === 0){
          window.vtoast.fail(`请选择单据`);
          throw new Error("请选择单据");
        }
        if(_.find(handleTicketList, item => item.ticketType !== handleTicketList[0]['ticketType'])){
          window.vtoast.fail(`需选择单据类型一致的数据`);
          throw new Error("需选择单据类型一致的数据");
        }
        if(this.handleActionType === '处理' && _.find(handleTicketList, item => _.includes(['完成', '拒绝'], item.ticketStatus))){
          window.vtoast.fail(`不能选择【完成、拒绝】的单据`);
          throw new Error("不能选择【完成、拒绝】的单据");
        }
      },
      async doHandleItem() {
        const { handleTicketList, handleTicketIds, handleActionType } = this;
        const ticketType = handleTicketList[0]['ticketType'];

        this.isTableLoading = true;
        switch (ticketType) {
          case '保养付款':
          case '保险付款':
          case '发车收款':
          case '退车付款':
            await this.$refs.handlePaymentRequest.doUiAction('startUpdateItem', { ticketIds: handleTicketIds, actionType: handleActionType });
            break;
          default:
            console.error("[openHandleItem] ticketType not find", { item });
            break;
        }
        this.isTableLoading = false;
      },
      // ---------- <<<<<<<<<<< 处理工单 uiAction ---------

      // ---------- table selected >>>>>>>>>>>> --------
      tableItemSelected({ item, value }) {
        if (value) {
          this.tableSelected.push(item);
        } else {
          this.tableSelected = _.reject(this.tableSelected, ['ticketId', item.ticketId]);
        }
      },
      tableToggleSelectAll({ items, value }) {
        if (value) {
          this.tableSelected = items;
        } else {
          this.tableSelected = [];
        }
      },
      // ---------- <<<<<<<<<<< table selected  --------
    }
  })
</script>

<style scoped>
  table td {
    white-space: nowrap;
    /* 将文本限制为单行 */
    max-width: 220px;
    /* 最大宽度为300px */
    overflow: hidden;
    /* 隐藏文本超出容器的部分 */
    text-overflow: ellipsis;
    /* 在文本溢出时添加省略号 */
  }

  table td.warp {
    white-space: pre-wrap !important;
  }

  body .theme--light.v-data-table>.v-data-table__wrapper>table>tbody>tr:hover:not(.v-data-table__expanded__content):not(.v-data-table__empty-wrapper),
  body .theme--light.v-data-table > .v-data-table__wrapper > table > tbody > tr:hover td.fixed,
  body .theme--light.v-data-table.fixed-first-column>.v-data-table__wrapper>table>tbody>tr:hover td:nth-child(1) {
    background: #FFFFFF !important;
  }
  .v-data-table__wrapper {
    padding-bottom: 20px;
  }
</style>
{% endblock %}
